//
//  YLCEasyImageAddViewController.m
//  LinYa
//
//  Created by 初程程 on 2018/5/4.
//  Copyright © 2018年 初程程. All rights reserved.
//

#import "YLCEasyImageAddViewController.h"
#import "YLCEasyImageAddCell.h"
#import "YLCEasyImageAddBottomView.h"
#import "YLCAddEasyImageViewController.h"
#import "SDPhotoBrowser.h"
#define EASY_CELL @"YLCEasyImageAddCell"
@interface YLCEasyImageAddViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,YLCEasyImageAddCellDelegate,SDPhotoBrowserDelegate>

@end

@implementation YLCEasyImageAddViewController
{
    UICollectionView *imageTable;
    UIButton *delegateBtn;
    UIButton *addBtn;
    UIButton *rightBtn;
    BOOL isEdit;
    NSInteger selectIndex;
    YLCEasyImageAddBottomView *bottomView;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self hiddenBottom];
    rightBtn.selected = NO;
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self hiddenBottom];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self initDataSource];
}
- (UIBarButtonItem *)rightBarButtonItem{
    
    rightBtn = [YLCFactory createLabelBtnWithTitle:@"编辑" titleColor:[UIColor whiteColor]];
    
    [rightBtn setTitle:@"取消" forState:UIControlStateSelected];
    
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
    [rightBtn addTarget:self action:@selector(gotoEdit:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    return rightBarItem;
}
- (void)gotoEdit:(UIButton *)sender{
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        [self showBottom];
    }else{
        [self hiddenBottom];
    }
    [imageTable reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    selectIndex = 0;
    [self createCustomView];
}
- (void)initDataSource{
    YLCAccountModel *model = [[YLCAccountManager shareManager] currentAccount];
    
    [YLCNetWorking loadNetServiceWithParam:@{@"userId":model.user_id,@"token":model.token,@"classifyId":_classifyId} method:@"POST" urlPath:@"app/sygt/gallery" delegate:self response:^(id responseObject, NSError *error) {
        if (error) {
            return ;
        }
        NSArray *list = responseObject;
        
        if (JK_IS_ARRAY_NIL(list)) {
            return;
        }
        
        NSMutableArray *container = [NSMutableArray arrayWithCapacity:0];
        
        for (NSDictionary *dict in list) {
            YLCEasyImageListModel *model = [YLCEasyImageListModel modelWithDict:dict];
            
            [container addObject:model];
        }
        _imageList = container.copy;
        
        [imageTable reloadData];
    }];
}

- (void)createCustomView{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    
    imageTable = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flow];
    
    imageTable.backgroundColor = YLC_COMMON_BACKCOLOR;
    
    [imageTable registerNib:[UINib nibWithNibName:@"YLCEasyImageAddCell" bundle:nil] forCellWithReuseIdentifier:EASY_CELL];
    
    imageTable.delegate = self;
    
    imageTable.dataSource = self;
    
    [self.view addSubview:imageTable];
    
    [imageTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsZero);
    }];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _imageList.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    YLCEasyImageAddCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:EASY_CELL forIndexPath:indexPath];
    
    if (indexPath.row<_imageList.count) {
        cell.model = _imageList[indexPath.row];
    }
    cell.isEdit = isEdit;
    
    cell.index = indexPath.row;
    
    cell.delegate = self;
    if (indexPath.row==selectIndex) {
        cell.isSelect = YES;
    }else{
        cell.isSelect = NO;
    }
    
    
    [cell configCell];
    
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (isEdit) {
        return;
    }
    SDPhotoBrowser *photoBrowser = [SDPhotoBrowser new];
    photoBrowser.delegate = self;
    photoBrowser.currentImageIndex = indexPath.row;
    photoBrowser.imageCount = _imageList.count;
    photoBrowser.sourceImagesContainerView = collectionView;
    [photoBrowser show];
}
- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index{
    YLCEasyImageListModel *model = _imageList[index];
    return [NSURL URLWithString:model.imgsrc];
}

- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index{
    YLCEasyImageAddCell * cell = (YLCEasyImageAddCell *)[imageTable cellForItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    return [cell getImageView].image;
    
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake((self.view.frameWidth-40)/3, (self.view.frameWidth-40)/3);
}
- (void)showBottom{
    if (!bottomView) {
        bottomView = [[YLCEasyImageAddBottomView alloc] initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, 60)];
        
        [bottomView.signal subscribeNext:^(id x) {
            NSString *type = x;
            if ([type isEqualToString:@"2"]) {
                [self gotoAddImage];
            }else{
                [self gotoDelete];
            }
        }];
    }
    if (!isEdit) {
        isEdit = YES;
        [bottomView show];
    }
    
}
- (void)hiddenBottom{
    if (isEdit) {
        isEdit = NO;
        [bottomView dissMiss];
    }
    
}
- (void)gotoAddImage{
    [self hiddenBottom];
    
    YLCAddEasyImageViewController *con = [[YLCAddEasyImageViewController alloc] init];
    
    con.classifyId = _classifyId;
    
    [self.navigationController pushViewController:con animated:YES];
}
- (void)gotoDelete{
    YLCAccountModel *userModel = [[YLCAccountManager shareManager] currentAccount];
    
    YLCEasyImageListModel *model = _imageList[selectIndex];
    
    if ([model.is_sys isEqualToString:@"1"]) {
        return;
    }
    
    [YLCNetWorking loadNetServiceWithParam:@{@"userId":userModel.user_id,@"token":userModel.token,@"classifyId":_classifyId,@"galleryId":model.id} method:@"POST" urlPath:@"app/sygt/delGallery" delegate:self response:^(id responseObject, NSError *error) {
        if (error) {
            return ;
        }
        selectIndex = 0;
        [SVProgressHUD showSuccessWithStatus:@"删除成功"];
        NSMutableArray *container = _imageList.mutableCopy;
        [container removeObject:model];
        _imageList = container.copy;
        [imageTable reloadData];
    }];
}
- (void)didSelectEditWithModel:(YLCEasyImageListModel *)model
                         index:(NSInteger)index{
//    NSMutableArray *container = _imageList.mutableCopy;
//
//    [container setObject:model atIndexedSubscript:index];
//
//    _imageList = container.copy;
    selectIndex = index;
    
    [imageTable reloadData];
}
- (NSString *)title{
    return @"图集库";
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
